<template>
    <div class="app-container">
        <el-form
            ref="bannerForm"
            label-width="130px"
            label-position="left"
            style="width: 730px;"
            :model="bannerForm"
            :rules="rules"
            class="demo-ruleForm"
        >
            <el-form-item>
                <div slot="label" style="margin-top: 120px">
                    <el-upload
                        class="upload-demo"
                        :action="uploadURL"
                        :show-file-list="false"
                        :before-upload="beforeImgUpload"
                        :on-success="handleImgSuccess"
                        name="image_upload"
                    >
                        <el-button type="primary">设置图片</el-button>
                        <div slot="tip" class="el-upload__tip"></div>
                    </el-upload>
                </div>
                <el-carousel indicator-position="none" height="300px">
                    <el-carousel-item v-loading="loading">
                        <img v-if="bannerForm.image" :src="bannerForm.image">
                        <h3 v-else class="small">1</h3>
                    </el-carousel-item>
                </el-carousel>
            </el-form-item>
            <el-form-item label="标题" style="margin-top: 30px">
                <el-input
                    v-model="bannerForm.keywords"
                    maxlength="36"
                    show-word-limit
                />
            </el-form-item>
            <el-form-item
                label="绑定文章ID"
                prop="newsId"
            >
                <el-input v-model.number="bannerForm.newsId" autocomplete="off" />
            </el-form-item>

            <el-table
                v-if="postData"
                :data="postData"
                style="width: 100%;margin-bottom: 35px;"
            >
                <el-table-column
                    prop="catName"
                    label="所属大类"
                    width="180"
                >
                </el-table-column>
                <el-table-column
                    prop="title"
                    label="文章标题"
                    width="280"
                >
                    <template slot-scope="{row}">
                        <router-link :to="'/post/edit/'+row.id">
                            <span class="link-type">{{ row.title }}</span>
                        </router-link>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="updateTime"
                    label="更新时间"
                >
                </el-table-column>
            </el-table>

            <el-form-item>
                <el-button :type="isEdit ? 'primary' : 'success'" @click="submitForm('bannerForm')">{{ isEdit ? '保存' : '创建' }}</el-button>
                <el-button @click="backToList">返回列表</el-button>
            </el-form-item>
        </el-form>

    </div>
</template>

<script>
import { getBannerDetail, getPostInfo, createBanner, updateBanner } from '@/api/banner'
import { validURL } from '@/utils/validate'

export default {
    name: 'BannerDetail',
    props: {
        isEdit: {
            type: Boolean,
            default: false
        }
    },

    data() {
        // 校验pid
        var validatePid = (rule, value, callback) => {
            if (value === '') {
                this.postData = null
                callback()
            } else if (isNaN(value)) {
                callback(new Error('文章id应为纯数字'))
            } else {
                getPostInfo(value).then(info => {
                    if (info) {
                        const arr = []
                        arr.push(info)
                        this.postData = arr
                        callback()
                    } else {
                        this.postData = null
                        callback(new Error('该文章id不存在'))
                    }
                })
            }
        }
        return {
            // 头像上传
            headers: {
                token: '*_~'
            },
            uploadURL: process.env.VUE_APP_BASE_API + '/banner/upload',
            loading: false,
            // 提交表单
            bannerForm: {
                keywords: '',
                newsId: '',
                image: ''
            },
            rules: {
                newsId: [{ validator: validatePid, trigger: ['blur', 'change'] }]
            },
            // 所选文章
            postData: null
        }
    },
    created() {
        if (this.isEdit) {
            const id = this.$route.params && this.$route.params.id
            this.fetchData(id)
        }
    },
    methods: {
        // 获取数据
        fetchData(id) {
            getBannerDetail(id).then(banner => {
                this.bannerForm = banner
                this.setPageTitle(id)
            }).catch(err => {
                console.log(err)
            })
        },
        setPageTitle(id) {
            const title = '编辑横幅'
            document.title = `${title} - ${id}`
        },
        // 横幅规格限定
        beforeImgUpload(file) {
            const types = ['image/jpeg', 'image/jpg', 'image/gif', 'image/bmp', 'image/png']
            const isIMG = types.includes(file.type)
            const isLt20M = file.size / 1024 / 1024 < 20

            if (!isIMG) {
                this.$message.error('上传横幅必须为图片格式!')
            }
            if (!isLt20M) {
                this.$message.error('上传图片大小不能超过 20MB!')
            }

            // 图片尺寸必须大于600x300, 宽高比必须为2:1
            let status = 0
            const isSize = new Promise(function(resolve, reject) {
                const width = 600
                const height = 300
                const _URL = window.URL || window.webkitURL
                const img = new Image()
                img.onload = function() {
                    if (img.width <= width || img.height <= height) {
                        status = 1 // 图片尺寸太小
                    } else if (img.width / img.height !== 2) {
                        status = 2 // 图片比例不对
                    }
                    status === 0 ? resolve() : reject()
                }
                img.src = _URL.createObjectURL(file)
            }).then(() => {
                this.loading = true // 开始轮播图加载圈
                return file
            }, () => {
                if (status === 1) {
                    this.$message.error('上传的图片尺寸必须大于600x300')
                } else if (status === 2) {
                    this.$message.error('上传的图片宽高比必须为2:1')
                }
                return Promise.reject()
            })

            // 判断是否满足条件提交图片
            return isIMG && isLt20M && isSize
        },
        handleImgSuccess(res, file) {
            setTimeout(() => {
                this.loading = false
                this.$message.success('图片上传成功!')
            }, 300)
            // this.imageUrl = URL.createObjectURL(file.raw)
            this.bannerForm.image = res.data.image_url
        },
        // 表单提交
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (!validURL(this.bannerForm.image)) {
                        this.$message.error('请先添加横幅图片!')
                        return false
                    }
                    if (this.isEdit) {
                        const id = this.$route.params && this.$route.params.id
                        updateBanner(id, this.bannerForm).then(() => {
                            this.$message.success('保存成功!')
                        })
                    } else {
                        createBanner(this.bannerForm).then(() => {
                            this.$message.success('横幅创建成功!')
                            setTimeout(() => {
                                this.backToList()
                                this.bannerForm = {
                                    keywords: '',
                                    newsId: '',
                                    image: ''
                                }
                            }, 1000)
                        })
                    }
                } else {
                    return false
                }
            })
        },
        // 返回列表
        backToList() {
            this.$router.push('/banner/list')
        }

    }
}
</script>

<style scoped lang="scss">
.app-container{
    padding: 30px 50px;
}
.el-carousel__item {
    background-color: #99a9bf;
    h3 {
        position: absolute;
        top: 40%;
        left: 50%;
        color: white;
        font-size: 18px;
        opacity: 0.75;
        margin: 0;
    }
    img {
        width: 100%;
    }
}

</style>
